﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FD.Tools.CopyAssist.Manager
{
    /**
     * Created By: Jackie Lee(天宇遊龍)
     * CreatedOn: 2018-02-06
     */
    /// <summary>
    /// 日志
    /// </summary>
    public class FDLogger
    {
        private readonly string path = "log";
        private readonly string logName = "publisher";

        private FDLogger() { }
        private static FDLogger _logger = new FDLogger();

        public static FDLogger Logger
        {
            get { return _logger; }
        }

        public void Info(string msg)
        {
            msg = FormatMsg(msg);
            Write(msg);
        }

        public void Error(string msg, Exception ex)
        {
            msg = FormatMsg($"{msg}\r\n{ex.Message}\r\n{ex.StackTrace}");
            Write(msg);
        }

        private void Write(string msg)
        {
            //Console.WriteLine(msg);
            try
            {
                using (FileStream fs = new FileStream(GetFileName(), FileMode.Append))
                {
                    StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.Write(msg);
                    sw.Flush();
                }
            }
            catch { }
        }

        private string FormatMsg(string msg)
        {
            return $"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] {msg}\r\n";
        }

        /// <summary>
        /// 文件名
        /// </summary>
        /// <returns></returns>
        private string GetFileName()
        {
            CheckDir();
            var fileName = $"{path}/{logName}_{DateTime.Now.ToString("yyyyMMdd")}.log";
            return fileName;
        }

        private void CheckDir()
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }
    }
}
